# -*- encoding:utf-8 -*-
# @Time: 2022/11/19 20:39
# @Author : moran
# @Email: moran@maqu.com
# @File: serializers.py
# @Software: PyCharm
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from .models import *


class ArticleSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    label_name = serializers.CharField(source='label.name', read_only=True)

    class Meta:
        model = Article
        exclude = ['is_delete']


class SonCommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    reply_username = SerializerMethodField()

    class Meta:
        model = Comment
        exclude = ['is_delete']

    def get_reply_username(self, comment):
        # 查询出被回复评论的用户的名字
        return Comment.objects.get(id=comment.reply_comment).user.username


class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    sonComment = SerializerMethodField()

    class Meta:
        model = Comment
        exclude = ['is_delete']

    def get_sonComment(self, comment):
        serializer = SonCommentSerializer(Comment.objects.filter(parent_comment=comment.id), many=True)
        data = serializer.data
        data.reverse()
        return data
